<?php

namespace App\Models\Order;

use App\Models\User\User;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class GoodsOrder extends Model
{
	use HasDateTimeFormatter;
    use SoftDeletes;

    protected $table = 'goods_orders';

    protected $guarded = [];

    protected $appends = [
        'status', 'remain_cnt',
    ];

    public function remainCnt() : Attribute
    {
        $samples = $this->samples;
        $result = 0;
        foreach ($samples as &$sample) {
            if ($sample->status == 1) {
                $result++;
            }
        }
        return Attribute::make(
            get: fn () => $result,
        );
    }

    public function status() : Attribute
    {
        $samples = $this->samples;
        $result = 0;
        $check1 = false;
        $check2 = false;
        $check3 = false;
        foreach ($samples as &$sample) {
            if ($sample->status == 1) {
                $check1 = true;
            } else if ($sample->status == 2) {
                $check2 = true;
            } else if ($sample->status == 3) {
                $check3 = true;
            }
        }
        if ($check1 && !$check2 && !$check3) {
            $result = 1;
        } else if (!$check1 && !$check2 && $check3) {
            $result = 3;
        } else {
            $result = 2;
        }
        return Attribute::make(
            get: fn () => $result,
        );
    }

    public function checkItems() : HasMany
    {
        return $this->hasMany(GoodsOrderCheckItem::class, 'order_id');
    }

    public function user() : BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function samples() : HasMany
    {
        return $this->hasMany(OrderSample::class, 'order_id');
    }

    public function refundOperator() : BelongsTo
    {
        return $this->belongsTo(User::class, 'refund_operator_id');
    }
}
